Completed
Push — master ( c8b881...0fa427 )
by Andres
54s
created

angular.service(ꞌutilꞌ)   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 3
c 3
b 0
f 0
nc 4
dl 0
loc 22
rs 9.2
nop 2
1
/* globals Ziggurat, Poisson */
2
/**
3
 util
4
 Utility service with misc. functions.
5
6
 @namespace Services
7
 */
8
'use strict';
9
10
angular
11
  .module('game')
12
  .service('util', ['prettyNumberFilter',
13
    '$sce',
14
    'data',
15
    function(prettyNumber, $sce, data) {
16
      this.gaussian = new Ziggurat();
17
      this.poisson = new Poisson();
18
19
      /* Return the HTML representation of an element, or the element itself
20
      if it doesn't have one */
21
      this.getHTML = function(resource) {
22
        let html = data.html[resource];
23
        if (typeof html === 'undefined') {
24
          html = data.resources[resource].html;
25
        }
26
        if (typeof html === 'undefined') {
27
          return resource;
28
        }
29
        return html;
30
      };
31
32
      this.prettifyNumber = function(number) {
33
        if (typeof number === 'undefined' || number === null) {
34
          return null;
35
        }
36
        if (number === '') {
37
          return '';
38
        }
39
        if (number === Infinity) {
40
          return '∞';
41
        }
42
        if (number > 1e6) {
43
          // Very ugly way to extract the mantisa and exponent from an exponential string
44
          let exponential = number.toPrecision(6).split('e');
45
          let exponent = parseFloat(exponential[1].split('+')[1]);
46
          // And it is displayed with superscript
47
          return Number.parseFloat(exponential[0]).toFixed(4) +
48
            ' &#215; 10<sup>' +
49
            this.prettifyNumber(exponent) +
50
            '</sup>';
51
        }
52
        // we use a regex to remove trailing zeros, plus . (if necessary)
53
        return prettyNumber(number, 4);
54
      };
55
56
      this.randomDraw = function(number, p) {
57
        let production;
58
        let mean = number * p;
59
        //if (p < 0.01) {
60
          // using Poisson distribution (would get slow for large numbers.
61
          // there are fast formulas but I don't know how good they are)
62
          //production = this.poisson.getPoisson(mean);
63
        //} else {
64
          // Gaussian distribution
65
          let q = 1 - p;
66
          let variance = number * p * q;
67
          let std = Math.sqrt(variance);
68
          production = Math.round(this.gaussian.nextGaussian() * std + mean);
69
        //}
70
        if (production > number) {
71
          production = number;
72
        }
73
        if (production < 0) {
74
          production = 0;
75
        }
76
        return production;
77
      };
78
79
      this.trustHTML = function(html) {
80
        return $sce.trustAsHtml(html);
81
      };
82
    }
83
  ]);
84